import Fastify from 'fastify';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import rateLimit from '@fastify/rate-limit';
import swagger from '@fastify/swagger';
import swaggerUi from '@fastify/swagger-ui';
import { AppDataSource } from './config/database';
import errorHandler from './middleware/errorHandler';
import authRoutes from './routes/auth';
import userRoutes from './routes/user';
import weatherRoutes from './routes/weather';
import { groupRoutes } from './routes/groups';
import { websiteRoutes } from './routes/websites';

// 创建 Fastify 实例
const fastify = Fastify({
  logger: {
    level: process.env.LOG_LEVEL || 'info',
    transport: process.env.NODE_ENV === 'development' ? {
      target: 'pino-pretty',
      options: {
        colorize: true,
        translateTime: 'HH:MM:ss Z',
        ignore: 'pid,hostname',
      },
    } : undefined,
  },
});

// 注册插件
async function registerPlugins() {
  // 安全插件
  await fastify.register(helmet, {
    contentSecurityPolicy: false,
  });

  // CORS 插件
  await fastify.register(cors, {
    // 允许的源
    origin: (origin, callback) => {
      const allowedOrigins = process.env.CORS_ORIGIN?.split(',') || [
        'http://localhost:3000',
        'http://localhost:3001',
        'http://127.0.0.1:3000',
        'http://127.0.0.1:3001'
      ];
      
      // 允许没有origin的请求（如移动应用、Postman等）
      if (!origin) return callback(null, true);
      
      // 开发环境允许所有localhost和127.0.0.1的请求
      if (process.env.NODE_ENV === 'development') {
        if (origin.includes('localhost') || origin.includes('127.0.0.1')) {
          return callback(null, true);
        }
      }
      
      // 检查是否在允许列表中
      if (allowedOrigins.includes(origin)) {
        return callback(null, true);
      }
      
      return callback(new Error('Not allowed by CORS'), false);
    },
    // 允许携带凭证
    credentials: true,
    // 允许的HTTP方法
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    // 允许的请求头
    allowedHeaders: [
      'Origin',
      'X-Requested-With',
      'Content-Type',
      'Accept',
      'Authorization',
      'Cache-Control',
      'X-HTTP-Method-Override'
    ],
    // 暴露的响应头
    exposedHeaders: [
      'Content-Length',
      'X-Kuma-Revision'
    ],
    // 预检请求的缓存时间（秒）
    maxAge: 86400, // 24小时
    // 处理预检请求
    preflightContinue: false,
    optionsSuccessStatus: 204
  });

  // 限流插件
  await fastify.register(rateLimit, {
    max: parseInt(process.env.RATE_LIMIT_MAX || '100'),
    timeWindow: process.env.RATE_LIMIT_WINDOW || '1 minute',
  });

  // Swagger 文档
  await fastify.register(swagger, {
    swagger: {
      info: {
        title: 'QianXun API',
        description: 'QianXun 后端服务 API 文档',
        version: '1.0.0',
      },
      schemes: ['http', 'https'],
      consumes: ['application/json'],
      produces: ['application/json'],
      securityDefinitions: {
        Bearer: {
          type: 'apiKey',
          name: 'Authorization',
          in: 'header',
        },
      },
    },
  });

  await fastify.register(swaggerUi, {
    routePrefix: '/docs',
    uiConfig: {
      docExpansion: 'full',
      deepLinking: false,
    },
    staticCSP: false, // 禁用静态CSP以避免连接限制
    transformStaticCSP: (header: string) => {
      // 允许连接到本地服务器
      return header.replace(
        "default-src 'self'",
        `default-src 'self'; connect-src 'self' http://localhost:${process.env.PORT || 3001}`
      );
    },
  });
}

// 注册错误处理
async function registerErrorHandler() {
  await fastify.register(errorHandler);
}

// 注册额外的CORS中间件
async function registerCorsMiddleware() {
  // 添加响应钩子来确保CORS头部正确设置
  fastify.addHook('onSend', async (request, reply, payload) => {
    // 确保响应包含必要的CORS头部（作为备用）
    if (!reply.getHeader('Access-Control-Allow-Origin')) {
      reply.header('Access-Control-Allow-Origin', request.headers.origin || '*');
    }
    if (!reply.getHeader('Access-Control-Allow-Credentials')) {
      reply.header('Access-Control-Allow-Credentials', 'true');
    }
    return payload;
  });
}

// 注册路由
async function registerRoutes() {
  await fastify.register(authRoutes, { prefix: '/api/auth' });
  await fastify.register(userRoutes, { prefix: '/api/users' });
  await fastify.register(weatherRoutes, { prefix: '/api' });
  await fastify.register(groupRoutes, { prefix: '/api/groups' });
  await fastify.register(websiteRoutes, { prefix: '/api/websites' });
}

// CORS插件已经处理了OPTIONS请求，无需额外的全局OPTIONS处理器

// 健康检查路由
fastify.get('/health', async (request, reply) => {
  return { status: 'ok', timestamp: new Date().toISOString() };
});

// 根路径路由
fastify.get('/', async (request, reply) => {
  return {
    name: 'QianXun API',
    version: '1.0.0',
    docs: '/docs',
    health: '/health',
  };
});

// 应用启动函数
export async function buildApp() {
  try {
    // 初始化数据库连接
    await AppDataSource.initialize();
    console.log('数据库连接成功');

    // 注册插件
    await registerPlugins();

    // 注册额外的CORS中间件
    await registerCorsMiddleware();

    // 注册错误处理
    await registerErrorHandler();

    // 注册路由
    await registerRoutes();

    return fastify;
  } catch (error) {
    console.error('应用启动失败:', error);
    throw error;
  }
}

export default fastify;